package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.dao.ISceneryCommentDAO;
import cn.wolfcode.luowowo.comment.dao.ISceneryReplyDAO;
import cn.wolfcode.luowowo.comment.domain.SceneryComment;
import cn.wolfcode.luowowo.comment.domain.SceneryReply;
import cn.wolfcode.luowowo.comment.query.SceneryCommentQuery;
import cn.wolfcode.luowowo.comment.query.SceneryReplyQuery;
import cn.wolfcode.luowowo.comment.service.ISceneryCommentService;
import cn.wolfcode.luowowo.comment.service.ISceneryReplyService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class SceneryReplyServiceImpl implements ISceneryReplyService {

    @Autowired
    private ISceneryReplyDAO sceneryReplyDAO;

    @Autowired
    private ISceneryCommentDAO sceneryCommentDAO;

    @Autowired
    private ISceneryCommentService sceneryCommentService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public SceneryReply save(SceneryReply reply) {
        if (reply.getId() == null) {
            reply.setCreateTime(new Date());
        }

        //关联回复
        if (reply.getRefReply() != null && StringUtils.hasLength(reply.getRefReply().getId())) {
            reply.setRefReply(this.get(reply.getRefReply().getId()));
        }

        sceneryReplyDAO.save(reply);

        return reply;
    }

    /**
     * 分页
     */
    @Override
    public List<SceneryReply> list() {
        return sceneryReplyDAO.findAll(Sort.by(Sort.Direction.DESC, "createTime"));
    }

    /**
     * 查单个
     *
     * @param id
     * @return
     */
    @Override
    public SceneryReply get(String id) {
        Optional<SceneryReply> op = sceneryReplyDAO.findById(id);
        return op.isPresent() ? op.get() : null;
    }

    @Override
    public Page<SceneryReply> query(SceneryReplyQuery qo) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), sort);
        return sceneryReplyDAO.findAll(pageable);
    }

    @Override
    public Page<SceneryReply> findReplyByCommentId(SceneryReplyQuery qo) {
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        PageRequest pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), sort);
        return sceneryReplyDAO.findByCommentId(qo.getCommentId(), pageable);
    }
}
